import { BasicDrawer, useDrawer, useDrawerInner } from "@/components/Drawer";
import { useState, useMemo } from "react";
import { BasicForm, useForm, FormSchema } from "@/components/Form";
import { PurchaseInApi } from "@/api/erp/purchase/in";
import { message, Tabs } from "antd";
import { useTranslation } from "react-i18next";
import { BasicProTable, useProTable } from "@/components/ViewComponents/proTable";
import { Button } from "antd";
import { WarehouseApi } from "@/api/erp/stock/warehouse";
import { AccountApi } from "@/api/erp/finance/account";
import StockInFormDetail from "./StockInFormDetail";
import { productApi } from "@/api/erp/drug/drug";
const newAdd = (props: { register: Fn }) => {
	const en_vi = "drugStorage.inventoryManagement";
	const { t } = useTranslation();
	let reload: Function;
	let buyinId: any;
	const [isUpdated, setIsUpdated] = useState(false);
	const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(props.register, data => {
		reload = data.reload;
		buyinId = data.record?.buyinId;
		resetFields();
		setDrawerProps({ confirmLoading: true });
		setIsUpdated(!!data?.isUpdated);
		data.isUpdated
			? setFieldsValue(data.record?.items)
			: setFieldsValue([
					{
						key: new Date().getTime(),
						whsId: undefined,
						productId: undefined,
						taxPercent: undefined,
						productUnitName: undefined,
						remark: undefined,
						count: 1,
						productPrice: undefined
					}
			  ]);
		setFieldsValueFn({
			...data.record
		});
		setDrawerProps({ confirmLoading: false });
	});
	const [drawerDetail, { openDrawer }] = useDrawer();
	const getTitle = useMemo(() => {
		return isUpdated ? t(`${en_vi}.warehouseInformation.editWarehouseInfo`) : t(`${en_vi}.warehouseInformation.addWarehouseInfo`);
	}, [isUpdated]);
	const formItems: FormSchema[] = [
		{
			label: t(`drugStorage.purchasingManagement.purchaseInventory.buyinId`),
			component: "Input",
			field: "buyinId",
			componentProps: {
				disabled: true,
				placeholder: t("drugStorage.automaticallySaving")
			}
		},
		{
			label: t(`drugStorage.purchasingManagement.purchaseInventory.inTime`),
			component: "DatePicker",
			field: "buyinTime"
		},
		{
			label: t(`drugStorage.salesManagement.saleOrder.orderId`),
			field: "orderId", // 二级抽屉待开发
			component: "InputSearch",
			componentProps: {
				onSearch: () => openDrawer(true)
			}
		},
		{
			label: t(`drugStorage.purchasingManagement.purchaseOrder.account`),
			component: "ApiSelect",
			field: "accountId",
			componentProps: {
				api: AccountApi.getAccountSimpleList,
				labelField: "name",
				valueField: "id",
				immediate: false
			}
		},
		{
			label: t(`drugStorage.purchasingManagement.purchaseOrder.discountPercent`),
			component: "InputNumber",
			field: "discountPercent"
		},
		{
			label: t(`drugStorage.purchasingManagement.purchaseInventory.otherPrice`),
			component: "InputNumber",
			field: "otherPrice"
		},
		{
			label: t(`${en_vi}.warehouseInformation.remark`),
			component: "InputTextArea",
			field: "remark",
			colProps: { span: 24 }
		},
		{
			label: t("drugStorage.attachment"),
			component: "FileUpload",
			field: "fileUrl",
			componentProps: {
				// fileType: "image",
				maxCount: 1
			}
		}
	];
	const [formTop, { validateFields, setFieldsValue: setFieldsValueFn, resetFields }] = useForm({
		schemas: formItems,
		labelWidth: 150,
		baseColProps: { span: 12 }
	});
	const dataSource = [
		{
			key: new Date().getTime(),
			whsId: undefined,
			productId: undefined,
			taxPercent: undefined,
			productUnitName: undefined,
			remark: undefined,
			count: 1,
			productPrice: undefined
		}
	];
	const defaultColumns = [
		{
			title: t("felix_ui.sq_numb"),
			// dataIndex: "sq_numb",
			render: (text, record, index) => index * 1 + 1 // 设置序号
		},
		{
			title: t("drugStorage.inventoryManagement.drugInventory.warehouseName"),
			dataIndex: "whsId",
			editable: true,
			// width: "20%",
			type: "ApiSelect",
			componentProps: {
				api: WarehouseApi.getWarehouseSimpleList,
				labelField: "name",
				valueField: "whsId"
			}
		},
		{
			title: t("drugStorage.productName"),
			dataIndex: "productId",
			editable: true,
			// width: "20%",
			type: "ApiSelect",
			componentProps: {
				api: productApi.getproductSimpleList,
				labelField: "productName",
				valueField: "productId",
				immediate: false,
				params: {
					bizType: "1"
				}
			}
		},
		{
			title: t("drugStorage.purchasingManagement.supplierInfo.taxPercent"),
			dataIndex: "taxPercent",
			editable: true
		},
		{
			title: t("drugStorage.inventoryManagement.drugInventory.unitName"),
			dataIndex: "productUnitName"
		},
		{
			title: t("felix_ui.remark"),
			dataIndex: "remark",
			editable: true
		},
		{
			title: t("drugStorage.inventoryManagement.drugInventory.count"),
			dataIndex: "count",
			editable: true
		},
		{
			title: t("drugStorage.inventoryManagement.drugInventory.salePrice"),
			dataIndex: "productPrice",
			editable: true
		},
		{
			title: t("felix_ui.action"),
			render: (_, obg) => {
				return <Button onClick={onDelete(obg)}>{t("felix_ui.delete")}</Button>;
			}
			// fixed: "right"
		}
	];
	const [proTable, { submit, handleAdd, handleDelete, setFieldsValue }] = useProTable({
		defaultColumns,
		dataSource
	});
	const onAdd = () => {
		handleAdd({
			key: new Date().getTime(),
			whsId: undefined,
			productId: undefined,
			taxPercent: undefined,
			productUnitName: undefined,
			remark: undefined,
			count: 1,
			productPrice: undefined
		});
	};
	const onDelete = obj => () => {
		handleDelete(obj.key);
	};
	const handleSubmit = async () => {
		const values = await validateFields();
		const items = await submit();
		values.buyinTime = new Date(values.buyinTime).getTime();
		values.items = items;
		// values.totalCount = 0;
		// values.totalPrice = 0;
		// items.map((item: any) => {
		// 	values.totalCount += item.count / 1;
		// 	values.totalPrice += item.productPrice / 1;
		// });
		let res;
		if (isUpdated) {
			values.buyinId = buyinId;
			res = await PurchaseInApi.updatePurchaseIn(values);
		} else {
			res = await PurchaseInApi.createPurchaseIn(values);
		}
		if (!res) {
			message.error(t("viewComponents.patientInformation.additionFailed"));
			return;
		}
		message.success(t("viewComponents.patientInformation.successfullyAdded"));
		closeDrawer();
		reload();
	};
	const setOrderItem = (orderItem: any) => {
		console.log("orderItem", orderItem);
		const newArr = orderItem.items.map((item: any, index: number) => {
			return { ...item, key: index + 1 };
		});
		console.log("newArr", newArr);
		setFieldsValueFn(orderItem);
		setFieldsValue(newArr);
	};
	return (
		<>
			<BasicDrawer size="large" {...props} title={getTitle} register={registerDrawer} ok={handleSubmit} showFooter={true}>
				<Tabs>
					<Tabs.TabPane tab={t("drugStorage.inventorydrugs")}>
						<BasicForm register={formTop}></BasicForm>
						<Button onClick={onAdd}> {t("felix_ui.add")}</Button>
						<div style={{ width: "100%", overflow: "auto" }}>
							<BasicProTable register={proTable}></BasicProTable>
						</div>
					</Tabs.TabPane>
				</Tabs>
			</BasicDrawer>
			<StockInFormDetail register={drawerDetail} setOrderItem={setOrderItem}></StockInFormDetail>
		</>
	);
};
export default newAdd;
